import 'dart:async';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/coin_product.dart';

class CoinPurchaseService {
  static final CoinPurchaseService _instance = CoinPurchaseService._internal();
  factory CoinPurchaseService() => _instance;
  CoinPurchaseService._internal();

  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  
  bool _isInitialized = false;
  bool get isInitialized => _isInitialized;
  
  // 购买状态回调
  Function(String productId, bool isLoading, String? error)? onPurchaseStateChanged;
  Function(int coins)? onCoinsAdded;
  
  Future<void> initialize() async {
    if (_isInitialized) return;
    
    final bool available = await _inAppPurchase.isAvailable();
    if (!available) {
      throw Exception('In-app purchase not available');
    }
    
    // 监听购买更新
    _subscription = _inAppPurchase.purchaseStream.listen(
      _handlePurchaseUpdates,
      onDone: () {
        _subscription.cancel();
      },
      onError: (error) {
        // 处理购买流错误
        onPurchaseStateChanged?.call('', false, 'Purchase stream error: $error');
      },
    );
    
    _isInitialized = true;
  }
  
  void dispose() {
    _subscription.cancel();
    _isInitialized = false;
  }
  
  Future<void> _handlePurchaseUpdates(List<PurchaseDetails> purchaseDetailsList) async {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      await _handlePurchaseDetail(purchaseDetails);
    }
  }
  
  Future<void> _handlePurchaseDetail(PurchaseDetails purchaseDetails) async {
    if (purchaseDetails.status == PurchaseStatus.pending) {
      // 购买等待中
      onPurchaseStateChanged?.call(purchaseDetails.productID, true, null);
    } else if (purchaseDetails.status == PurchaseStatus.error) {
      // 购买失败
      onPurchaseStateChanged?.call(purchaseDetails.productID, false, purchaseDetails.error?.message);
      await _finalizePurchase(purchaseDetails);
    } else if (purchaseDetails.status == PurchaseStatus.purchased || 
               purchaseDetails.status == PurchaseStatus.restored) {
      // 购买成功
      await _verifyAndDeliverPurchase(purchaseDetails);
    } else if (purchaseDetails.status == PurchaseStatus.canceled) {
      // 购买取消
      onPurchaseStateChanged?.call(purchaseDetails.productID, false, null);
      await _finalizePurchase(purchaseDetails);
    }
  }
  
  Future<void> _verifyAndDeliverPurchase(PurchaseDetails purchaseDetails) async {
    try {
      // 验证购买（这里可以添加服务器验证逻辑）
      final CoinProduct? product = CoinProduct.findByProductId(purchaseDetails.productID);
      if (product != null) {
        // 添加金币到用户账户
        await _addCoinsToAccount(product.coins);
        onCoinsAdded?.call(product.coins);
        
        // 延时2秒后完成订单，防止影响下次购买
        await Future.delayed(const Duration(seconds: 2));
        onPurchaseStateChanged?.call(purchaseDetails.productID, false, null);
      }
      
      // 完成购买
      await _finalizePurchase(purchaseDetails);
    } catch (e) {
      onPurchaseStateChanged?.call(purchaseDetails.productID, false, 'Failed to deliver purchase: $e');
      await _finalizePurchase(purchaseDetails);
    }
  }
  
  Future<void> _finalizePurchase(PurchaseDetails purchaseDetails) async {
    if (purchaseDetails.pendingCompletePurchase) {
      await _inAppPurchase.completePurchase(purchaseDetails);
    }
  }
  
  Future<void> _addCoinsToAccount(int coins) async {
    final prefs = await SharedPreferences.getInstance();
    final currentCoins = prefs.getInt('user_coins') ?? 0;
    await prefs.setInt('user_coins', currentCoins + coins);
  }
  
  Future<int> getUserCoins() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getInt('user_coins') ?? 0;
  }
  
  Future<void> setUserCoins(int coins) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt('user_coins', coins);
  }
  
  Future<void> purchaseProduct(CoinProduct product) async {
    if (!_isInitialized) {
      throw Exception('Purchase service not initialized');
    }
    
    try {
      // 设置购买状态为加载中
      onPurchaseStateChanged?.call(product.productId, true, null);
      
      // 查询产品详情
      final ProductDetailsResponse response = await _inAppPurchase.queryProductDetails({product.productId});
      
      if (response.error != null) {
        onPurchaseStateChanged?.call(product.productId, false, 'Failed to query product: ${response.error!.message}');
        return;
      }
      
      if (response.productDetails.isEmpty) {
        onPurchaseStateChanged?.call(product.productId, false, 'Product not found');
        return;
      }
      
      final ProductDetails productDetails = response.productDetails.first;
      final PurchaseParam purchaseParam = PurchaseParam(productDetails: productDetails);
      
      // 发起购买
      final bool success = await _inAppPurchase.buyConsumable(purchaseParam: purchaseParam);
      
      if (!success) {
        onPurchaseStateChanged?.call(product.productId, false, 'Failed to initiate purchase');
      }
    } catch (e) {
      onPurchaseStateChanged?.call(product.productId, false, 'Purchase error: $e');
    }
  }
  
  Future<void> restorePurchases() async {
    if (!_isInitialized) {
      throw Exception('Purchase service not initialized');
    }
    
    try {
      await _inAppPurchase.restorePurchases();
    } catch (e) {
      throw Exception('Failed to restore purchases: $e');
    }
  }
  
  // 检查是否有未完成的购买
  Future<void> checkPendingPurchases() async {
    if (!_isInitialized) return;
    
    try {
      // 恢复购买来检查未完成的交易
      await _inAppPurchase.restorePurchases();
    } catch (e) {
      // 忽略错误，这只是一个检查操作
    }
  }
} 